package obj;

import data.DataHelper;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Templ implements Comparable<Templ> {

    public static final String BASE_URL = "http://extramobi.ru/product/";

    public String vendor;
    public List<String> models;
    public List<String> modelUrls;
    public int price;
    public int count;
    public int oldPrice;

    public static final String TEMPLS_PATH = "data/%s/%s.xls";

    public int compareTo(Templ templ) {
        return vendor.compareTo(templ.vendor);
    }

    public static List<Templ> parseTempls(String templName, String type, int price) throws BiffException, IOException {
        Workbook workbook = Workbook.getWorkbook(new File(String.format(TEMPLS_PATH, templName, templName)));
        Sheet sheet = workbook.getSheet(0);
        List<Templ> templs = new ArrayList<Templ>();
        for (int j = 0; j < Integer.MAX_VALUE; j++) {
            String vendor = null;
            try {
                vendor = sheet.getCell(j, 0).getContents();
            } catch (ArrayIndexOutOfBoundsException e) {
                break;
            }
            if (vendor.length() == 0) {
                break;
            }
            Templ templ = new Templ();
            templ.vendor = vendor;
            templ.price = price;
            templ.count = 100;
            List<String> models = new ArrayList<String>();
            List<String> modelUrls = new ArrayList<String>();
            for (int i = 1; i < Integer.MAX_VALUE; i++) {
                String model = null;
                try {
                    model = sheet.getCell(j, i).getContents();
                } catch (ArrayIndexOutOfBoundsException e) {
                    break;
                }
                if (model.length() == 0) {
                    break;
                }
                models.add(model);
                String modelUrl = DataHelper.codeInURL(BASE_URL + type + "_" + templ.vendor + "_" + model.replaceAll("\\.", ""));
                modelUrls.add(modelUrl);
            }
            templ.models = models;
            templ.modelUrls = modelUrls;
            templs.add(templ);
        }
        Collections.sort(templs);
        return templs;
    }

}
